package com.songsong.myblog2.controller;

import com.alibaba.fastjson.JSON;
import com.songsong.myblog2.domain.Archives;
import com.songsong.myblog2.service.ArchivesService;
import com.songsong.myblog2.service.ArticleService;
import com.songsong.myblog2.util.TransCodingUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/archives")
public class ArchivesController {
    /*注入archivesService*/
    @Resource(name = "archivesService")
    private ArchivesService archivesService;
    /*注入articleService*/
    @Resource(name = "articleService")
    private ArticleService articleService;

    /**/
    /*
     * 跳转到归档页
     * */
    @RequestMapping("/toArchives")
    public String toArchives() {
        return "anon/archives";
    }

    /*获取所有归档*/
    @RequestMapping("/getAllArchives")
    @ResponseBody
    public String getAllArchives() {
        List<Archives> allArchives = archivesService.getAllArchives();
        String archives = JSON.toJSONString(allArchives);
        return archives;
    }

    /**
     * 分页获得该归档日期下的文章
     *
     * @param archive
     * @param request
     * @return
     */
    @GetMapping("/getArticleByArticle")
    @ResponseBody
    public JSONObject getArchiveArticle(@RequestParam("archive") String archive,
                                        HttpServletRequest request) {
        try {
            archive = TransCodingUtil.unicodeToString(archive);
        } catch (Exception e) {
        }
        int rows = Integer.parseInt(request.getParameter("rows"));
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));
        return articleService.findArticleByArchive(archive, rows, pageNum);
    }
}
